from pathlib import Path
import requests
import json
import re

path = Path('./settings.json')
settings = json.loads(path.read_text(encoding='utf-8'))
print(f'经过读取首选项，我们识别到你希望下载{f'原图，并将其压缩成{settings['width']}x{settings['height']}尺寸的图片' if settings['UHD'] is True else 'FHD尺寸的图片'}')
print(f'并且你希望下载{settings['area']}地区的图片')
a = True
while a:
    try:
        print('起始索引是指从今天开始往前数第几天的图片,0为今日，数量是指从起始索引开始往前数的几天的图片')
        idx, n=map(int, input('请输入你希望下载的图片起始索引和数量（用空格隔开）：').split())
        if n > 8:
            print('数量不能超过8')
            continue
        else:
            if idx < 0:
                print('起始索引不能小于0')
                continue
            else:
                if idx > 2:
                    print('起始索引不能大于2')
                    continue
                else:
                    a = False
    except:
        print('请输入正确的数字格式')
        continue

url = f'http://cn.bing.com/HPImageArchive.aspx?format=js&idx={idx}&n={n}&mkt={settings["area"]}&uhd={'1' if settings['UHD'] is True else '0'}'
response = requests.get(url).json()
images = response['images']
if len(images) == 0:
    print('没有找到图片')
    exit()
else:
    print(f'共找到{len(images)}张图片')

data = []

if settings['UHD'] is True:
    if settings['resize'] is True:
        for i in images:
            data.append({
                'title': i['title'],
                'copyright': i['copyright'],
                'url': f'https://cn.bing.com' + re.sub(r'&pid=.*$', f'&w={settings['width']}&h={settings['height']}', i['url']),
                'date': i['enddate']
            })
            print(f'正在保存链接，标题：{i["title"]}')
    else:
        for i in images:
            data.append({
                'title': i['title'],
                'copyright': i['copyright'],
                'url': f'https://cn.bing.com' + re.sub(r'&pid=.*$', '', i['url']),
                'date': i['enddate']
            })
            print(f'正在保存链接，标题：{i["title"]}')
        

else:
    for i in images:
        data.append({
            'title': i['title'],
            'copyright': i['copyright'],
            'url': f'https://cn.bing.com' + i['url'], 
            'date': i['enddate']
        })
        print(f'正在保存链接，标题：{i["title"]}')

print('链接保存完毕')
output = Path('./output.json')
output.write_text(json.dumps(data, ensure_ascii=False, indent=4, separators=(',', ':'), sort_keys=True), encoding='utf-8')
print('已保存到 output.json')

download = input('是否下载图片（y/n）：').lower()
if download == 'y':
    for i in data:
        print(f'正在下载图片，标题：{i["title"]}   ', end='')
        try:
            with open(f'./{i['title']}.jpg', 'wb') as f:
                f.write(requests.get(i['url']).content)
            f.close()
            print('完成')
        except Exception as e:
            print('失败', e)
    print('图片下载完毕')
